/*
 * @Date: 2019-10-13 14:05:24
 * @Author: jiangsenlin
 * @Description: 一个帮助类函数
 */




/**
 * @description: 数组去重
 * @param {Array}: arry 
 * @param {String}: key 如果存在key  对象数组去重
 * @return: 
 * @example: 
 */
export const uniqueAraayObj = (arry, key) => {
    var n = {};
    var r = [];

    key ? arry.map(function (item) {
        if (!n[item[key]]) {
            n[item[key]] = true;
            r.push(item);
        }
    }) : arry.map(function (item) {
        if (!n[item]) {
            n[item] = true;
            r.push(item);
        }
    });
    return r;
}

/**
 * @description: 快排
 * @param {Array}: arry 
 * @return: 
 * @example: 
 */
export const quickSort = arr => {
    if (arr.length <= 1) {//如果数组长度小于等于1无需判断直接返回即可
        return arr;
    }
    var pivotIndex = Math.floor(arr.length / 2);//取基准点
    var pivot = arr.splice(pivotIndex, 1)[0];//取基准点的值,splice(index,1)函数可以返回数组中被删除的那个数
    var left = [];//存放比基准点小的数组
    var right = [];//存放比基准点大的数组
    for (var i = 0; i < arr.length; i++) { //遍历数组，进行判断分配
        if (arr[i] < pivot) {
            left.push(arr[i]);//比基准点小的放在左边数组
        } else {
            right.push(arr[i]);//比基准点大的放在右边数组
        }
    }
    //递归执行以上操作,对左右两个数组进行操作，直到数组长度为<=1；
    return quickSort(left).concat([pivot], quickSort(right));
};


/**
 * @description: 取差集
 * @param {Array}: AllArray  所有集合
 * @param {Array}: curentArray  当前集合
 * @return: {Array}: 差集
 * @example: 
 */
export const getDifference = (AllArray, curentArray) => {
    if (Array.isArray(AllArray) && Array.isArray(curentArray)) {
        return selectProductList.filter(ea => reallySelectedRows.every(eb => eb.skuId !== ea.skuId))
    }
}



/**
 * @description: 数组分类
 * @param {Array}:arr
 * @param {String}: Catekey  归类的key   Catekey = 'id'
 * @param {String}: childrenKeyName  归类组名称 childrenKeyName = 'children'
 * @return: 
 * @example: var  arr = [
    {"id":"1001","name":"值1","value":"111"},
    {"id":"1001","name":"值1","value":"11111"},
    {"id":"1002","name":"值2","value":"25462"},
    {"id":"1002","name":"值2","value":"23131"},
    {"id":"1002","name":"值2","value":"2315432"},
    {"id":"1003","name":"值3","value":"333333"}
];
getArrayClassification(arr,'id','children')
 */

export const getArrayClassification = (arr, Catekey, childrenKeyName) => {
    let map = {}
    let dest = []
    for (let i = 0; i < arr.length; i++) {
        let ai = arr[i];
        if (!map[ai[Catekey]]) {
            let obj = {}
            obj[Catekey] = ai[Catekey]
            obj[childrenKeyName] = [ai]
            dest.push(obj);
            map[ai[Catekey]] = ai;
        } else {
            for (let j = 0; j < dest.length; j++) {
                let dj = dest[j];
                if (dj[Catekey] == ai[Catekey]) {
                    dj[childrenKeyName].push(ai);
                    break;
                }
            }
        }
    }
    return dest
}



/*
 * 数字四舍五入位数格式(处理浮点数小数问题)
 * cal: 需要处理的数字或字符串数字
 * e: 保留小数位数, 为0的位数会去掉, 默认不传使用2位
 */

export const roundFormat = (cal, e) => {
    if (isNaN(cal)) {
        return 0;
    }
    if (e == null) {
        e = 2;
    }
    var time = Math.pow(10, e);
    return Math.round(cal * time) / time;
}



/**
 * 异步延迟函数
 *
 * @export
 * @param {*} timeout
 * @returns {Promise}
 */
export const delay = timeout =>
    new Promise(resolve => {
        setTimeout(resolve, timeout)
    })

export const sleep = delay

/**
 * 为Promise包装一个cancel方法，让其变得可取消
 * @param {Promise} promise
 * @returns {Promise}
 */
export const makeCancelablePromise = promise => {
    let rejectFn

    const wrappedPromise = new Promise((resolve, reject) => {
        rejectFn = reject

        Promise.resolve(promise)
            .then(resolve)
            .catch(reject)
    })

    wrappedPromise.cancel = () => {
        promise.__canceled = true
        rejectFn({ canceled: true })
    }

    return wrappedPromise
}

/**
 * 判断一个函数是否是一个生成器函数
 * @param {Function} fn
 * @returns {Boolean}
 */
export const isGeneratorFunction = fn => {
    return fn && Object.prototype.toString.call(fn) === '[object GeneratorFunction]'
}

let uniqueIdIndex = 0

/**
 * 生成不重复的唯一ID字符串
 * @param {string} prefix 可选的前缀
 * @returns {string}
 */
export const generateUnid = (prefix = '') => {
    return `${prefix}${(
        Math.random()
            .toString(13)
            .split('.')[1] || ''
    ).slice(0, 8)}${(uniqueIdIndex += 1)}`
}

/**
 * 判断空数组
 * @param {Array} array 需要判断的数组
 * @returns {boolean}
 */

export const emptyArray = array => {
    let empty = false
    if (!(array instanceof Array)) {
        array = []
    }
    empty = array.length === 0
    return empty
}

/**
 * 判断空对象
 * @param {Object} object 需要判断的对象
 * @returns {boolean}
 */
export const emptyObject = object => {
    let empty = false
    if (!(object instanceof Object)) {
        object = {}
    }
    empty = Object.keys(object).length === 0
    return empty
}

/**
 * 判断空字符串
 * @param {String} string 需要判断的字符串
 * @returns {boolean}
 */
export const emptyString = string => {
    let empty = false
    if (!(typeof string === 'string')) {
        string = ''
    }
    if (typeof string === 'undefined' || string == null || string === '') {
        empty = true
    }

    return empty
}

export const isEmptyValue = value => {
    return typeof value === 'undefined' || value == null || value === ''
}

/**
 * 获取URL参数
 * @param {string} search URL中所带的参数
 * @returns {object}
 */

export const getURLParams = search => {
    search = search || location.search
    const list = search.split('?')
    if (!emptyArray(list) && list.length > 1) {
        const item = list[1]
        let items = item.split('&')

        if (emptyArray(items)) {
            items = []
        }
        const newParams = {}
        items.map(rs => {
            const param = rs.split('=')

            if (!emptyArray(param)) {
                let key = ''
                let value = ''

                if (param.length === 1) {
                    key = param[0]
                } else if (param.length === 2) {
                    key = param[0]
                    value = param[1]
                }
                newParams[key] = value
            }
        })
        return newParams
    } else {
        return {}
    }
}
// 获取url search 中的参数
// 单个参数
export const getURLParam = ({ search, name }) => {
    const $search = search || window.location.search
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') //构造一个含有目标参数的正则表达式对象
    var r = $search.substr(1).match(reg) //匹配目标参数
    if (r !== null) return r[2]
    return null //返回参数值
}









